<?php

namespace app\controller\api;

use app\controller\ApiBaseController;
use app\model\LawUserModel;
use think\response\Json;

class Lawuser extends ApiBaseController
{

    /**
     * 用户注册
     *
     * @return Json
     */
    public function register(): Json
    {
        try {
            // $intSex = param_filter($this->request->param('sex', 0), 'int');
            // if (empty($intSex)) {
            //     return api_response([], '请选择性别', 0);
            // }
            // $strIdCode = param_filter($this->request->param('id_code', ''), 'string');
            // if (empty($strIdCode)) {
            //     return api_response([], '缺少用户唯一识别号', 0);
            // }
            // $strParentIdCode = param_filter($this->request->param('parent_id_code', ''), 'string');
            // $intOrganizationId = param_filter($this->request->param('organization_id', ''), 'int');
            // if (empty($intOrganizationId)) {
            //     return api_response([], '缺少组织 id', 0);
            // }
            // // 用户名
            // $strName = param_filter($this->request->param('name', ''), 'string');
            // if (empty($strName)) {
            //     return api_response([], '请输入用户名', 0);
            // }
            // // 邮箱
            // $strEmail = param_filter($this->request->param('email', ''), 'string');
            // if(empty($strEmail)){
            //     return api_response([], '请输入邮箱', 0);
            // }
            // // 用户明文密码(存储需要加密)
            // $strPassword = param_filter($this->request->param('password', ''), 'string');
            // if (empty($strPassword)) {
            //     return api_response([], '请输入密码', 0);
            // }
            // // 用户头像(可以为空)
            // $strAvatarUrl = param_filter($this->request->param('avatar_url', ''), 'string');

            // 微信union_id
            $strUnionId = param_filter($this->request->param('union_id', ''), 'string');
            if (!empty($strUnionId)) {
                // 检测微信是否已绑定其他账号
                $arrUserInfo = LawUserModel::getOneByWhere([
                    ['union_id', '=', $strUnionId]
                ]);
                if (!empty($arrUserInfo)) {
                    return api_response([], '微信账号已存在', 0);
                }
            }
            // 手机号 
            $strPhone = param_filter($this->request->param('phone', ''), 'string');
            if (!empty($strPhone)) {
                $arrUserInfo = LawUserModel::getOneByWhere([
                    ['phone', '=', $strPhone]
                ]);
                if (!empty($arrUserInfo)) {
                    return api_response([], '手机号已存在', 0);
                }
            }
            if (!empty($strPhone)) { //传入手机号，要求必须传入验证码
                // 短信验证码
                $strVerifyCode = param_filter($this->request->param('verify_code', ''), 'string');
                if (empty($strVerifyCode)) {
                    return api_response([], '请传入手机号和验证码', 0);
                }
                $boolCheck = checkVerifyCodeIsOk($strPhone, $strVerifyCode); //验证码验证
                if (!$boolCheck) {
                    return api_response([], '验证码错误', 0);
                }
            }

            // 手机号或微信union_id，必传一个
            if (empty($strPhone) && empty($strUnionId)) {
                return api_response([], '请传入手机号或微信union_id', 0);
            }


            // //根据父级 id_code，查到父 user_id
            // if (!empty($strParentIdCode)) {
            //     $arrParentUserInfo = LawUserModel::getOneByWhere([
            //         ['id_code', '=', $strParentIdCode]
            //     ]);
            //     if (empty($arrParentUserInfo)) {
            //         return api_response([], '未查到推荐人信息', 0);
            //     }
            // }

            // // 检测用户名是否已存在
            // $arrUserInfo = LawUserModel::getOneByWhere([
            //     ['name', '=', $strName]
            // ]);
            // if (!empty($arrUserInfo)) {
            //     return api_response([], '用户名已存在', 0);
            // }

            $modelLawUser = new LawUserModel();
            //添加用户
            $boolAddUser = $modelLawUser->addUser([
                'union_id' => $strUnionId,
                // 'sex' => $intSex,
                'phone' => $strPhone,
                // 'parent_user_id' => $arrParentUserInfo['id'] ?? 0,
                // 'organization_id' => $intOrganizationId,
                // 'name' => $strName,
                // 'email' => $strEmail,
                // 'hashed_password'=> password_hash($strPassword, PASSWORD_DEFAULT),
                // 'avatar_url'=> $strAvatarUrl,
                'id_code' => md5($strUnionId . $strPhone . time()),
                'status' => LawUserModel::STATUS_NORMAL,
                'role' => LawUserModel::ROLE_REGIST_YES,
                'create_time' => date('Y-m-d H:i:s'),
                'update_time' => date('Y-m-d H:i:s'),
            ]);

            if (!$boolAddUser) {
                return api_response([], '注册失败', 0);
            }
            return api_response([], '注册成功', 1);
        } catch (\Exception $e) {
            return api_response([], '注册失败：' . $e->getMessage(), 0);
        }
    }

    /**
     * 获取用户信息
     *
     * @return Json
     */
    public function getInfo(): Json
    {
        try {
            // 接收参数
            $strUnionId = param_filter($this->request->param('union_id', ''), 'string');
            $strPhone = param_filter($this->request->param('phone', ''), 'string');
            $strIdCode = param_filter($this->request->param('id_code', ''), 'string');

            $arrWhere = [];
            if (!empty($strUnionId)) {
                $arrWhere[] = ['union_id', '=', $strUnionId];
            }
            if (!empty($strPhone)) {
                $arrWhere[] = ['phone', '=', $strPhone];
            }
            if (!empty($strIdCode)) {
                $arrWhere[] = ['id_code', '=', $strIdCode];
            }
            if (empty($arrWhere)) {
                return api_response([], '请传入用户唯一识别号', 0);
            }
            $arrLawUserInfo = LawUserModel::getOneByWhere($arrWhere);
            if (empty($arrLawUserInfo)) {
                return api_response([], '未获取到用户信息', 0);
            }
            $arrRetData = [
                'union_id' => $arrLawUserInfo['union_id'],
                'name' => $arrLawUserInfo['name'],
                'sex' => $arrLawUserInfo['sex'],
                'phone' => $arrLawUserInfo['phone'],
                'id_code' => $arrLawUserInfo['id_code'],
                'current_points' => $arrLawUserInfo['current_points'],
                // 'parent_user_id' => $arrLawUserInfo['parent_user_id'],
                // 'organization_id' => $arrLawUserInfo['organization_id'],
                'status' => LawUserModel::getStatusText($arrLawUserInfo['status']),
                'role' => $arrLawUserInfo['role'],
                'create_time' => $arrLawUserInfo['create_time'],
                'update_time' => $arrLawUserInfo['update_time'],
            ];
            return api_response($arrRetData, '请求成功', 1);
        } catch (\Exception $e) {
            return api_response([], '获取用户信息失败：' . $e->getMessage(), 0);
        }
    }

    /**
     * 更新用户信息
     *
     * @return Json
     */
    public function upUserInfo(): Json
    {
        try {
            // 接收参数
            $strIdCode = param_filter($this->request->param('id_code', ''), 'string');
            if (empty($strIdCode)) {
                return api_response([], '缺少用户唯一识别号', 0);
            }
            $arrUpdata = [];
            $strUnionId = param_filter($this->request->param('union_id', ''), 'string');
            if (!empty($strUnionId)) {
                $arrUpdata['union_id'] = $strUnionId;
            }
            $strName = param_filter($this->request->param('name', ''), 'string');
            if (!empty($strName)) {
                $arrUpdata['name'] = $strName;
            }
            $intSex = param_filter($this->request->param('sex', 0), 'int');
            if (!empty($intSex)) {
                $arrUpdata['sex'] = $intSex;
            }
            $strPhone = param_filter($this->request->param('phone', ''), 'string');
            if (empty($strPhone)) {
                $arrUpdata['phone'] = $strPhone;
            }
            if (!empty($strPhone)) {
                $strVerifyCode = param_filter($this->request->param('verify_code', ''), 'string');
                if (empty($strVerifyCode)) {
                    return api_response([], '请传入手机号和验证码', 0);
                }
                $boolCheck = checkVerifyCodeIsOk($strPhone, $strVerifyCode); //验证码验证
                if (!$boolCheck) {
                    return api_response([], '验证码错误', 0);
                }
            }

            $strParentIdCode = param_filter($this->request->param('parent_id_code', ''), 'string');
            if (!empty($strParentIdCode)) {
                $arrParentUserInfo = LawUserModel::getOneByWhere([['id_code', '=', $strParentIdCode]]);
                if (empty($arrParentUserInfo)) {
                    return api_response([], '未获取到推荐人信息', 0);
                }
                $arrUpdata['parent_user_id'] = $arrParentUserInfo['id'];
            }
            $intOrganizationId = param_filter($this->request->param('organization_id', ''), 'int');
            if (!empty($intOrganizationId)) {
                $arrUpdata['organization_id'] = $intOrganizationId;
            }

            if (empty($arrUpdata)) {
                return api_response([], '没有需要更新的信息', 0);
            }

            LawUserModel::updateOneByWhere([['id_code', '=', $strIdCode]], $arrUpdata);

            return api_response();
        } catch (\Exception $e) {
            return api_response([], '更新用户信息失败：' . $e->getMessage(), 0);
        }
    }

    /**
     * 登录
     *
     * @return Json
     */
    public function login(): Json
    {
        try {
            //微信账号登录
            $strUnionId = param_filter($this->request->param('union_id', ''), 'string');
            if (!empty($strUnionId)) {
                $arrLawUserInfo = LawUserModel::getOneByWhere([['union_id', '=', $strUnionId]]);
                if (empty($arrLawUserInfo)) {
                    return api_response([], '用户不存在', 0);
                }
            }

            //手机号登录
            $strPhone = param_filter($this->request->param('phone', ''), 'string');
            if (!empty($strPhone)) {
                $arrLawUserInfo = LawUserModel::getOneByWhere([['phone', '=', $strPhone]]);
                if (empty($arrLawUserInfo)) {
                    return api_response([], '用户不存在', 0);
                }
            }

            if (empty($arrLawUserInfo)) {
                return api_response([], '未获取到用户信息', 0);
            }

            $arrTokenData = [
                'id_code' => $arrLawUserInfo['id_code'],
            ];
            // 创建访问令牌
            $strAccessToken = createAccessToken($arrTokenData);


            //返回前端
            return api_response([
                'user' => [
                    'id_code' => $arrLawUserInfo['id_code'],
                    'name' => $arrLawUserInfo['name'],
                    'current_points' => $arrLawUserInfo['current_points'],
                    'role' => $arrLawUserInfo['role'],
                ],
                'access_token' => $strAccessToken,
                'token_type' => 'bearer',
            ]);
        } catch (\Exception $e) {
            return api_response([], '登录失败：' . $e->getMessage(), 0);
        }
    }

    /**
     * 刷新用户令牌
     *
     * @return Json
     */
    public function refreshToken(): Json
    {
        try {
            // 获取用户令牌
            $strAccessToken = param_filter($this->request->param('access_token', ''), 'string');
            if (empty($strAccessToken)) {
                return api_response([], '缺少用户令牌', 0);
            }

            // 解析用户令牌
            try {
                $arrTokenData = parseAccessToken($strAccessToken);
            } catch (\Exception $e) {
                return api_response([], '无效的刷新令牌', 0);
            }

            // 检查令牌是否过期
            if ($arrTokenData['exp'] < time()) {
                return api_response([], '令牌已过期，请重新登录', 0);
            }
            // 检查用户是否存在
            $strIdCode = $arrTokenData['id_code'] ?? '';
            if (empty($strIdCode)) {
                return api_response([], '令牌数据异常', 0);
            }

            $arrLawUserInfo = LawUserModel::getOneByWhere([['id_code', '=', $strIdCode]]);
            if (empty($arrLawUserInfo)) {
                return api_response([], '用户不存在', 0);
            }

            // 生成新的访问令牌
            $arrNewTokenData = [
                'id_code' => $arrLawUserInfo['id_code'],
            ];
            $strNewAccessToken = createAccessToken($arrNewTokenData);

            // 返回新的令牌
            return api_response([
                'access_token' => $strNewAccessToken,
                'token_type' => 'bearer',
            ], '令牌刷新成功', 1);
        } catch (\Exception $e) {
            return api_response([], '刷新用户令牌失败：' . $e->getMessage(), 0);
        }
    }
}
